<template>
  <div>    
    <a-modal :visible="showAddUserStocks" 
      :width="280"
      :closable="true"
      @cancel="cancelAddUserStockView"> 
      <div style="padding:1em 1.5em;">
        <div class="u-item">
          <div style="margin: 0 auto; font-weight: 700;font-size: 1.2em;width:100%;text-align: center;
            padding: 0 1.5em;position: relative;">
           选择分组
          </div>
          <span style="display: inline-block;cursor: pointer;font-weight: 500;font-size: 14px;" @click="{editFlag = !editFlag;
            userPagesList.forEach(item=>item.edit = false);}">
              <span v-if="!editFlag">编辑</span>
              <span v-if="editFlag" style="color: #999;">退出编辑</span>
            </span>
            <a-list :data-source="userPagesList" item-layout="horizontal">
              <template #renderItem="{ item }">
                <a-list-item v-if="!item.edit">
                  <a-checkbox :checked="isUserPageChecked(item)" @change="toggleUserPageChecked(item)">
                    <span style="font-size: 14px;">{{ item.pageName }}&nbsp;({{ item.stockNum }})
                      <span v-if="!(item.pageName=='我的自选股' || item.pageName=='我的持仓') && editFlag"
                      @click="{item.edit=true;}">&nbsp;<EditOutlined/></span>
                    </span>
                  </a-checkbox>
                </a-list-item>
                <a-list-item v-else>
                  <a-checkbox></a-checkbox>
                  <a-input placeholder="输入分组名，回车确认" v-model:value="item.pageName"
                    style="margin-left: .5em;" @pressEnter="newUserPageEnter(item)"></a-input>
                </a-list-item>
              </template>
            </a-list>
         </div>
      </div>
      <template #footer>
        <div v-if="!editFlag">
          <a-button key="back" @click="addNewUserPage" :icon="h(PlusSquareFilled)" style="width:100px">新建分组</a-button>
          <a-button key="submit" type="primary" style="width:130px; padding-left: 24px; " @click="saveUserStock" :loading="submiting"><span style="padding: 0 1em;">确定</span></a-button>
        </div>
        <div v-if="editFlag">
          <a-button @click="deleteUserPageEvent" type="primary" style="width:240px">删除分组</a-button>
        </div>
        <div style="height:12px; width:100%;"></div>
      </template>
    </a-modal>
    </div>
</template>

<script lang="ts">
  import { message, Popconfirm, Input, Table, Button, Modal, List, ListItem, Checkbox } from 'ant-design-vue';
  import {EditOutlined} from '@ant-design/icons-vue'
  export default {
    components: {
      AButton: Button,
      AInput: Input,
      ATable: Table,
      Popconfirm: Popconfirm,
      AModal: Modal,
      AList: List,
      AListItem: ListItem,
      ACheckbox: Checkbox
    },
  };
</script>
<script lang="ts" setup>
  import { ref, onMounted, onUnmounted, h } from 'vue';
  import { PlusSquareFilled } from '@ant-design/icons-vue';
  import {getCurrentUserId} from '../../utils/currentUser'
  import { addUserStocks, getUserPages, addUserPage, deleteUserPage } from '/@/api/stock/userStocksDao';
  interface UserPageType {
    pageName: String,
    pageNr: Number,
    checked: Boolean
  };

  defineExpose({showAddUserStockView, cancelAddUserStockView});
  const emit = defineEmits(['refreshZixuanStatus'])

  onMounted(()=>{

  });

  onUnmounted(()=>{

  });

  const showAddUserStocks = ref(false);
  const userPagesList:UserPageType = ref([]);
  const addUserStockSource = ref(1);
  const selectedRowKeys = ref([]);
  const submiting = ref(false);
  const editFlag = ref(false);

  function switchEditStatusEvent(){
    for(var i=0; i<userPagesList.value.length; i++){
      let page = userPagesList.value[i];
      page.edit = true;
    }
  }

  function showAddUserStockView(source, selectedStocks) {
    addUserStockSource.value = source;
    selectedRowKeys.value = selectedStocks;
    loadUserPages();
    showAddUserStocks.value = true;
  }

  function cancelAddUserStockView() {
    showAddUserStocks.value = false;
    selectedRowKeys.value = [];
    editFlag.value = false;
  }
  function isUserPageChecked(item) {
    var page = userPagesList.value.find(d=>d.pageName==item.pageName);
    return page.checked;
  }
  function toggleUserPageChecked(item) {
    var page = userPagesList.value.find(d=>d.pageName==item.pageName);
    page.checked = !page.checked;
  }
  function addNewUserPage() {
    userPagesList.value.push({
      pageName:'',
      stockNum:0,
      checked: false,
      edit: true
    });
  };
  async function deleteUserPageEvent() {
    let ids = [];
    for(var i=0; i<userPagesList.value.length; i++) {
      let item = userPagesList.value[i];
      if(!item.checked){
        continue;
      }
      if(item.pageName=='我的自选股' || item.pageName=='我的持仓') {
        message.error(item.pageName+'不能删除');
        return;
      }
      ids.push(item.id);
    }

    await deleteUserPage({"ids":ids});
    message.success('删除成功');
    loadUserPages();
  }
  /**
   * 调用接口添加分组
   * @param e 
   */
  async function newUserPageEnter(item) {
    if(!item.pageName.trim()) {
      message.error('请输入分组名称')
      return ;
    }
    let result = await addUserPage({}, {
      id: item.id,
      userId:getCurrentUserId(),
      pageName: item.pageName
    });
    if(result) {
      message.error(result);
      return ;
    }
    let res = await getUserPages({
      "userId":getCurrentUserId()
    });
    userPagesList.value = [];
    for(var i=0; i<res.length; i++) {
        var data:UserPageType = res[i];
        data.checked = false;
        if(i==0) {
          data.checked = true;
        }
        if(data.pageName==item.pageName) {
          data.tempare = true;
        }
        userPagesList.value.push(data);
    }
  };

  async function loadUserPages() {
    let res = await getUserPages({
      "userId": getCurrentUserId()
    });
    userPagesList.value = [];
    if(res&&res.length>0) {
      for(var i=0; i<res.length; i++) {
        var data:UserPageType = res[i];
        data.checked = false;
        if(i==0) {
          data.checked = true;
        }
        userPagesList.value.push(data);
      }
    }
  }

  /**
   * 添加自选股dao
   */
  async function saveUserStock() {
    let stocks = [...selectedRowKeys.value];
    if(stocks.length==0) {
      message.error('请选择股票');
      return;
    }
    submiting.value = true;
    var pages = userPagesList.value.filter(item=>item.checked).map(item=>item.pageName);
    await addUserStocks({}, {
      "userId": getCurrentUserId(),
      "pageNames":pages,
      "stockCodes": stocks
    });
    submiting.value = false;
    message.success('添加成功');
    showAddUserStocks.value = false;
    if(addUserStockSource.value==2) {
      emit('refreshZixuanStatus', stocks);
    }
  }
</script>

<style lang="less" scoped>
  /deep/.ant-modal-footer {
    text-align: left !important;
  }
  .ant-modal-close-x {
    width:32px;
  }
</style>